<template>
  <div class="my-properties-page">
    <el-container>
      <el-header class="page-header">
        <div class="header-content">
          <h2>我的房源</h2>
          <el-button type="primary" @click="$router.push('/publish-property')">
            <el-icon><Plus /></el-icon>
            发布房源
          </el-button>
        </div>
      </el-header>

      <el-main>
        <el-card class="filter-card" shadow="never">
          <el-form :model="filters" inline>
            <el-form-item label="房源状态">
              <el-select v-model="filters.status" placeholder="全部状态" clearable @change="fetchList">
                <el-option label="全部" value="" />
                <el-option label="可租" value="available" />
                <el-option label="已租" value="rented" />
                <el-option label="已售" value="sold" />
                <el-option label="已下架" value="hidden" />
              </el-select>
            </el-form-item>
            <el-form-item label="房源类型">
              <el-select v-model="filters.room_type" placeholder="全部类型" clearable @change="fetchList">
                <el-option label="全部" value="" />
                <el-option label="公寓" value="apartment" />
                <el-option label="别墅" value="villa" />
                <el-option label="写字楼" value="office" />
                <el-option label="商铺" value="shop" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="resetFilters">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="list-card" shadow="never">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>

          <div v-else-if="list.length === 0" class="empty-container">
            <el-empty description="暂无房源">
              <el-button type="primary" @click="$router.push('/publish-property')">
                发布房源
              </el-button>
            </el-empty>
          </div>

          <div v-else class="properties-list">
            <div class="property-item" v-for="item in list" :key="item.id">
              <div class="property-image">
                <img :src="getCoverImage(item.images)" :alt="item.title" />
                <div class="status-badge" :class="getStatusClass(item.status)">
                  {{ getStatusText(item.status) }}
                </div>
              </div>
              
              <div class="property-info">
                <div class="property-header">
                  <h3 class="property-title">{{ item.title }}</h3>
                  <div class="property-price">
                    <span class="price">￥{{ item.price }}</span>
                    <span class="unit">/月</span>
                  </div>
                </div>
                
                <div class="property-meta">
                  <div class="meta-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ item.city }} {{ item.district }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><House /></el-icon>
                    <span>{{ item.area }}㎡</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Grid /></el-icon>
                    <span>{{ item.bedrooms }}室{{ item.living_rooms }}厅{{ item.bathrooms }}卫</span>
                  </div>
                </div>
                
                <div class="property-address">
                  <el-icon><MapLocation /></el-icon>
                  <span>{{ item.address }}</span>
                </div>
                
                <div class="property-description">
                  <p>{{ item.description || '暂无描述' }}</p>
                </div>
                
                <div class="property-footer">
                  <div class="property-time">
                    <el-icon><Clock /></el-icon>
                    <span>发布于 {{ formatDate(item.created_at) }}</span>
                  </div>
                  <div class="property-actions">
                    <el-button size="small" @click="viewProperty(item.id)">查看</el-button>
                    <el-button size="small" type="primary" @click="editProperty(item)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteProperty(item)">删除</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="pagination" v-if="total > 0">
            <el-pagination
              v-model:current-page="page"
              :page-size="pageSize"
              :total="total"
              layout="total, prev, pager, next"
              @current-change="fetchList"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { propertiesAPI } from '@/api/properties'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const list = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

const filters = reactive({
  status: '',
  room_type: ''
})

const getCoverImage = (images) => {
  if (images && images.length > 0) {
    return images[0]
  }
  return 'https://picsum.photos/seed/house/300/200'
}

const getStatusText = (status) => {
  const statusMap = {
    available: '可租',
    rented: '已租',
    sold: '已售',
    hidden: '已下架'
  }
  return statusMap[status] || '未知'
}

const getStatusClass = (status) => {
  const classMap = {
    available: 'status-available',
    rented: 'status-rented',
    sold: 'status-sold',
    hidden: 'status-hidden'
  }
  return classMap[status] || 'status-hidden'
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const fetchList = async () => {
  try {
    loading.value = true
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...filters
    }
    
    const res = await propertiesAPI.getUserProperties(params)
    if (res?.success) {
      list.value = res.data.items
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取房源列表失败:', error)
    ElMessage.error('获取房源列表失败')
  } finally {
    loading.value = false
  }
}

const resetFilters = () => {
  filters.status = ''
  filters.room_type = ''
  page.value = 1
  fetchList()
}

const viewProperty = (id) => {
  router.push(`/properties/${id}`)
}

const editProperty = (property) => {
  // 跳转到编辑页面，传递房源数据
  router.push({
    path: '/publish-property',
    query: { 
      id: property.id,
      edit: true 
    }
  })
}

const deleteProperty = async (property) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除房源"${property.title}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const res = await propertiesAPI.delete(property.id)
    if (res?.success) {
      ElMessage.success('房源删除成功')
      fetchList()
    } else {
      ElMessage.error(res?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除房源失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.my-properties-page {
  min-height: 100vh;
  background: #f6f8fb;
}

.page-header {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.filter-card {
  margin-bottom: 16px;
}

.list-card {
  min-height: 400px;
}

.loading-container {
  padding: 20px;
}

.empty-container {
  padding: 40px 20px;
}

.properties-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.property-item {
  display: flex;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: all 0.3s;
}

.property-item:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  transform: translateY(-2px);
}

.property-image {
  position: relative;
  width: 200px;
  height: 150px;
  flex-shrink: 0;
}

.property-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.status-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}

.status-available {
  background: #52c41a;
}

.status-rented {
  background: #faad14;
}

.status-sold {
  background: #ff4d4f;
}

.status-hidden {
  background: #8c8c8c;
}

.property-info {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.property-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.property-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.property-price {
  text-align: right;
}

.price {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.unit {
  font-size: 14px;
  color: #8c8c8c;
  margin-left: 4px;
}

.property-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 14px;
}

.property-address {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.property-description {
  flex: 1;
  margin-bottom: 8px;
}

.property-description p {
  margin: 0;
  color: #666;
  font-size: 14px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.property-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

.property-time {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #8c8c8c;
  font-size: 12px;
}

.property-actions {
  display: flex;
  gap: 8px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style>
